<template>
  <div class="relative w-full h-full pb60">
    <div class="h-full overflow-y-auto">
      <div class="border-bottom mb12">
        <PageHeader :title="title">
          <template #right>
            <el-button type="primary" @click="goBack" size="small">
              <SvgIcon name="iconfanhui" color="#fff" class="mr4" />{{ t('coupon.返回上级页面') }}
            </el-button>
          </template>
        </PageHeader>
      </div>

      <LangTabs v-model="lang" />
      <el-form ref="formRef" :model="form" :rules="rules" label-width="200px">
        <div class="titleRow pl10 mb15">{{ t('coupon.优惠券基本信息') }}</div>

        <el-form-item :label="t('coupon.优惠券名称')" :prop="['name' + lang]">
          <el-input
            v-model="form['name' + lang]"
            maxlength="20"
            show-word-limit
            style="width: 320px"
            :placeholder="t('coupon.请输入')"
          />
        </el-form-item>
        <el-form-item :label="t('coupon.适用商品')" prop="skuType">
          <div>
            <el-radio-group v-model="form.skuType">
              <el-radio :label="1">{{ t('coupon.全部商品可用') }}</el-radio>
              <el-radio :label="2">{{ t('coupon.指定分类可用') }}</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item
          :label="t('coupon.商品分类')"
          prop="skuClassifyIds"
          v-if="form.skuType === 2"
        >
          <el-cascader
            v-model="form.skuClassifyIds"
            :options="categoryOptions"
            :props="categoryProps"
            collapse-tags
            clearable
          />
        </el-form-item>

        <el-form-item :label="t('coupon.优惠券金额')" prop="discountMinus">
          <div class="flex_aic">
            <span>{{ t('coupon.减免') }}</span>
            <el-input-number
              v-model="form.discountMinus"
              controls-position="right"
              :min="0"
              style="width: 200px; margin: 0 10px"
            />
            <span>{{ t('coupon.元') }}</span>
          </div>
        </el-form-item>

        <el-form-item :label="t('coupon.消费门槛')" prop="discountLimit">
          <div>
            <div class="flex_aic">
              <span>{{ t('coupon.订单满') }}</span>
              <el-input-number
                v-model="form.discountLimit"
                controls-position="right"
                :min="0"
                style="width: 200px; margin: 0 10px"
              />
              <span>{{ t('coupon.元') }}</span>
            </div>
            <div class="color-999999 fs-12">
              {{ t('coupon.订单满多少元时可以使用此优惠券0元代表无使用门槛不包含运费') }}
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="t('coupon.每人限领')" prop="perVipCountLimit" v-if="type != 1">
          <div class="flex_aic">
            <el-input-number
              v-model="form.perVipCountLimit"
              controls-position="right"
              :min="1"
              style="width: 200px; margin: 0 10px"
            />
            <span>{{ t('coupon.次') }}</span>
          </div>
        </el-form-item>

        <el-form-item :label="t('coupon.发放总量')" prop="stock" v-if="type != 1">
          <el-input-number
            v-model="form.stock"
            controls-position="right"
            :min="1"
            style="width: 200px; margin: 0 10px"
          />
        </el-form-item>

        <el-form-item :label="t('coupon.领取时间')" prop="activityTime" v-if="type != 1">
          <el-date-picker
            v-model="form.activityTime"
            type="datetimerange"
            :range-separator="t('coupon.至')"
            :start-placeholder="t('coupon.开始时间')"
            :end-placeholder="t('coupon.结束时间')"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px"
            class="flex-grow-0"
          />
        </el-form-item>
        <el-form-item :label="t('coupon.使用时间')" prop="useTime">
          <el-date-picker
            v-model="form.useTime"
            type="datetimerange"
            :range-separator="t('coupon.至')"
            :start-placeholder="t('coupon.开始时间')"
            :end-placeholder="t('coupon.结束时间')"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px"
            class="flex-grow-0"
          />
        </el-form-item>

        <div v-if="type == 1">
          <el-form-item :label="t('coupon.每人发放')" prop="type1PerVipCount">
            <div class="flex_aic">
              <el-input-number
                v-model="form.type1PerVipCount"
                controls-position="right"
                :min="1"
                style="width: 200px; margin: 0 10px"
              />
              <span>{{ t('coupon.张') }}</span>
            </div>
          </el-form-item>
          <div class="titleRow pl10 mt15 mb15">{{ t('coupon.发放用户') }}</div>
          <el-form-item :label="t('coupon.选择用户')" prop="vipIds">
            <el-transfer
              v-model="form.vipIds"
              :data="vipList"
              :titles="[t('coupon.待选用户'), t('coupon.已选用户')]"
              filterable
              :filter-method="filterMethod"
              :filter-placeholder="t('coupon.请输入用户名')"
              :props="{
                key: 'id',
                label: 'nickName',
              }"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 底部按钮 -->
    <div class="fixed-bottom">
      <el-button @click="goBack">{{ t('coupon.返回') }}</el-button>
      <el-button type="primary" @click="handleSubmit" v-if="!isWatch"
        >{{ t('coupon.保存') }}</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import LangTabs from "@/components/LangTabs.vue";
import { setAttrLangs } from "@/i18n/tools";
import moment from "moment";

const { t, locale } = useI18n();
const lang = ref(locale.value);
const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const id = ref(route.query.id);
const type = ref(route.query.type);
const isWatch = ref(route.query.isWatch);
const categoryProps = computed(() => ({
  multiple: true,
  label: 'name' + lang.value,
  value: 'id'
}))
const form = ref({
  skuClassifyIds: [],
  discountLimit: 0,
  perVipCountLimit: 1,
  type1PerVipCount: 1,
  discountMinus: 0,
  useTime: "",
  skuType: 1,
  stock: 0,
  activityTime: "",
  vipIds: [],
});

setAttrLangs(form.value, "name", "");
const title = computed(() => {
  const nameMap = {
    1: t('coupon.点对点'),
    2: t('coupon.商品分类'),
    3: t('coupon.新人'),
  };

  return (
    (isWatch.value ? t('coupon.查看') : id.value ? t('coupon.编辑') : t('coupon.新增')) +
    nameMap[type.value] +
    t('coupon.优惠券')
  );
});
// 模拟商品分类数据
const categoryOptions = ref([]);
const vipList = ref([]);
const validate_discountMinus = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('coupon.请输入优惠券金额')))
  } else {
    if(form.value.discountMinus && form.value.discountLimit <= form.value.discountMinus){
      callback(new Error(t('coupon.消费门槛必须大于优惠券减免金额')))
    }
      formRef.value.clearValidate('discountLimit')
    callback()
  }
}
const validate_discountLimit = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('coupon.请输入订单满多少元时可以使用此优惠券')))
  } else {
    if(form.value.discountMinus && form.value.discountLimit <= form.value.discountMinus){
      callback(new Error(t('coupon.消费门槛必须大于优惠券减免金额')))
    }
      formRef.value.clearValidate('discountMinus')
    callback()
  }
}
const rules = ref({
  skuClassifyIds: [
    { required: true, message: t('coupon.请选择商品分类'), trigger: "change" },
  ],
  stock: [{ required: true, message: t('coupon.请输入发放总量'), trigger: "blur" }],
  discountLimit: [
    { validator: validate_discountLimit, trigger: 'change' }
  ],
  perVipCountLimit: [
    { required: true, message: t('coupon.请输入每人限领次数'), trigger: "blur" },
  ],
  type1PerVipCount: [
    { required: true, message: t('coupon.请输入每人发放张数'), trigger: "blur" },
  ],
  discountMinus: [
    { validator: validate_discountMinus, trigger: 'change' }
  ],
  useTime: [{ required: true, message: t('coupon.请选择到期时间'), trigger: "change" }],
  activityTime: [
    { required: true, message: t('coupon.请选择领取时间'), trigger: "change" },
  ],
  vipIds: [{ required: true, message: t('coupon.请选择发放用户'), trigger: "change" }],
});

setAttrLangs(rules.value, "name", [
  { required: true, message: t('coupon.请输入优惠券名称'), trigger: "blur" },
]);

const goBack = () => {
  router.back();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid) => {
    if (valid) {
      const { activityTime, useTime, ...rest } = form.value;
      const skuClassifyIds =
        form.value?.skuClassifyIds?.map((item) => item[item.length - 1]) || [];
      const params = {
        ...rest,
        activityTimeStart: activityTime[0]
          ? moment(activityTime[0], "YYYY-MM-DD HH:mm:ss").toISOString()
          : undefined,
        activityTimeEnd: activityTime[1]
          ? moment(activityTime[1], "YYYY-MM-DD HH:mm:ss").toISOString()
          : undefined,
        useTimeStart: useTime[0]
          ? moment(useTime[0], "YYYY-MM-DD HH:mm:ss").toISOString()
          : undefined,
        useTimeEnd: useTime[1]
          ? moment(useTime[1], "YYYY-MM-DD HH:mm:ss").toISOString()
          : undefined,
        skuClassifyIds,
        type: type.value,
      };
      Api.coupon_add(params).then((res) => {
        if (res.status === 200) {
          ElMessage.success(t('coupon.保存成功'));
          goBack();
        }
      });
    }
  });
};

const getSkuClassify = async () => {
  const res = await Api.businessCategory()
  categoryOptions.value = res.data || [];
};
const filterMethod = (query, item) => {
  return item?.nickName?.indexOf(query) > -1;
};
const getVipList = async() => {
 await Api.vip_list({
    page: 0,
    size: 999,
  }).then((res) => {
    vipList.value = res.data.content || [];
  });
};

const getCouponDetail = () => {
  Api.coupon_detail(id.value).then((res) => {
    form.value = {
      ...res.data,
      vipIds: []
    };
    if (res.data.activityTimeStart && res.data.activityTimeEnd) {
      form.value.activityTime = [
        moment(res.data.activityTimeStart).format("YYYY-MM-DD HH:mm:ss"),
        moment(res.data.activityTimeEnd).format("YYYY-MM-DD HH:mm:ss"),
      ];
    }
    if (res.data.useTimeStart && res.data.useTimeEnd) {
      form.value.useTime = [
        moment(res.data.useTimeStart).format("YYYY-MM-DD HH:mm:ss"),
        moment(res.data.useTimeEnd).format("YYYY-MM-DD HH:mm:ss"),
      ];
    }
    if(res.data.vips?.length > 0){
      form.value.vipIds = res.data?.vips?.map(item => item.id) || []
    }
    if(res.data.skuClassifys?.length > 0){
      form.value.skuClassifyIds = res.data.skuClassifys.map(v=> ([v.skuClassifyParentId, v.skuClassifyId]))
    }

    console.log("form.value===", form.valu);
    
  });
};
onMounted(async() => {
  await getSkuClassify();
  if (type.value == 1) {
    await getVipList();
  }
  if (id.value) {
    getCouponDetail();
  }
});
</script>

<style lang="scss" scoped>
.border-bottom {
  width: 100%;
  border-bottom: 1px solid #e5e5e5;
}

.titleRow {
  width: 100%;
  height: 36px;
  border-radius: 2px;
  background: #fffaf7;
  line-height: 36px;
}

.fixed-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 0;
  text-align: center;
  background: #fff;
  border-top: 1px solid #e5e5e5;
}

.pb60 {
  padding-bottom: 60px;
}

:deep(.el-form-item__label) {
  &:before {
    content: "*";
    color: #ff4d4f;
  }
}
</style>
